package com.itsu.app.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itsu.app.exception.MyException;
import com.itsu.app.interceptor.UserThreadLocal;
import com.itsu.interfaces.entity.Sound;
import com.itsu.interfaces.entity.UserInfoEntity;
import com.itsu.interfaces.service.SoundService;
import com.itsu.pojo.constants.Constants;
import com.itsu.pojo.enums.ResultCode;
import com.itsu.pojo.results.ErrorResult;
import com.itsu.pojo.vo.SoundVo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Service
public class AppSoundService {

    @Reference
    SoundService soundService;

    @Autowired
    AppUserInfoService appUserInfoService;

    @Autowired
    FastFileStorageClient storageClient;

    @Autowired
    FdfsWebServer fdfsWebServer;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    public void saveSound(MultipartFile soundFile) {
        if (ObjectUtil.isEmpty(soundFile)) {
            throw new MyException(new ErrorResult(ResultCode.VIDEO_NULL));
        }

        String soundType = StrUtil.subAfter(soundFile.getOriginalFilename(), ".", true);
        if (!StrUtil.equalsAnyIgnoreCase(soundType, "mp3", "m4a", "mp4")) {
            throw new MyException(new ErrorResult(ResultCode.PHOTO_FORMART_ERROR));
        }

        if ((soundFile.getSize() / 1024 / 1024) > 5) {
            throw new MyException(new ErrorResult(ResultCode.PHOTO_SIZE_ERROR));
        }
        Sound sound = null;
        try {
            sound = new Sound();
            sound.setUserId(UserThreadLocal.getUid());
            sound.setSoundUrl(uploadFile(soundFile.getInputStream(), soundFile.getSize(), soundType));
            sound.setCreated(System.currentTimeMillis());
        } catch (IOException e) {
            e.printStackTrace();
        }

        soundService.saveSound(sound);
    }

    public SoundVo getSound() {
        String num = redisTemplate.opsForValue().get(Constants.SOUND_UPPER_LIMIT + UserThreadLocal.getUid());
        if ("0".equals(num)) {
            return SoundVo.builder().remainingTimes(0).build();
        }
        Integer intNum = Convert.toInt(num);
        Sound sound = soundService.randomOther(UserThreadLocal.getUid());

        if (ObjectUtil.isEmpty(sound)) {
            throw new MyException(new ErrorResult(ResultCode.USER_REGIT_ERROR));
        }

        UserInfoEntity entity = appUserInfoService.findUserByUid(sound.getUserId());
        if (ObjectUtil.isEmpty(entity)) {
            throw new MyException(new ErrorResult(ResultCode.USER_REGIT_ERROR));
        }

        SoundVo soundVo = new SoundVo();
        soundVo.setId(sound.getUserId());
        soundVo.setAvatar(entity.getLogo());
        soundVo.setNickname(entity.getNickName());
        soundVo.setGender(entity.getSex() == 1 ? "woman" : "man");
        soundVo.setAge(entity.getAge());
        soundVo.setSoundUrl(sound.getSoundUrl());
        soundVo.setRemainingTimes(intNum - 1);

        redisTemplate.opsForValue().set(Constants.SOUND_UPPER_LIMIT + UserThreadLocal.getUid(), Convert.toStr(intNum - 1));
        return soundVo;
    }

    private String uploadFile(InputStream file, Long fileSize, String fileSuffixName) {
        StorePath storePath = storageClient.uploadFile(file, fileSize, fileSuffixName, null);
        return fdfsWebServer.getWebServerUrl() + "/" + storePath.getFullPath();
    }
}
